package com.iiapk.gridnew;

import java.io.ByteArrayOutputStream;
import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iiapk.gridnew.util.TokenStore;
import com.tencent.weibo.api.T_API;
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.Configuration;
import com.tencent.weibo.utils.OAuthClient;

public class OAuthActivity extends Activity {
	
	public static final int NONE = 0;  
    public static final int PHOTOHRAPH = 1;// 拍照   
    public static final int PHOTOZOOM = 2; // 缩放   
    public static final int PHOTORESOULT = 3;// 结果   
    public static final String IMAGE_UNSPECIFIED = "image/*";
    
    public static final int WEIBO_MAX_LENGTH = 140;

	private OAuth oauth;
	private OAuthClient auth;
	private String clientIp="";
	private String mPicPath = "";
	
	private EditText postContentText;
	private FrameLayout mPiclayout;
	private ImageView image;
	private TextView mTextNum;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.qq_index);
		
		postContentText = (EditText) findViewById(R.id.postContentText);
		postContentText.setText(WebViewPagerActivity.content);
		mPiclayout = (FrameLayout)findViewById(R.id.qq_flPic);
		image = (ImageView)this.findViewById(R.id.qq_ivImage);
		mTextNum = (TextView)this.findViewById(R.id.qq_tv_text_limit);
		
		postContentText.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,int after) {
			}
			public void onTextChanged(CharSequence s, int start, int before,int count) {
				String mText = postContentText.getText().toString();
				int len = mText.length();
				if (len <= WEIBO_MAX_LENGTH) {
					len = WEIBO_MAX_LENGTH - len;
					mTextNum.setTextColor(R.color.text_num_gray);
				}
				else {
					len = len - WEIBO_MAX_LENGTH;
					mTextNum.setTextColor(Color.RED);
				}
				mTextNum.setText(String.valueOf(len));
			}
		});

		findViewById(R.id.qq_postBtn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg) {
				T_API tapi = new T_API();
				String content = postContentText.getText().toString();
				if(TextUtils.isEmpty(content))
					return;
				try {
					if(TextUtils.isEmpty(mPicPath))
						tapi.add(oauth, "json", content, clientIp, "", "");
					else
						tapi.add_pic(oauth, "json", content, clientIp, mPicPath);
					mPiclayout.setVisibility(View.INVISIBLE);
					Toast.makeText(OAuthActivity.this, R.string.send_sucess, Toast.LENGTH_LONG).show();;	
					finish();
				} catch (Exception e) {
					Toast.makeText(OAuthActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();;
				}
			}
		});
		
		findViewById(R.id.qq_btnClose).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg) {
				finish();
			}
		});
		this.findViewById(R.id.qq_btn_insert_topic).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				String _text = postContentText.getText().toString();
				_text+="#"+getText(R.string.weibo_btn_topic)+"#";
				postContentText.setText(_text);
			}
		});
		this.findViewById(R.id.qq_btn_insert_at).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				String _text = postContentText.getText().toString();
				_text+="@"+getText(R.string.weibo_btn_at);
				postContentText.setText(_text);
			}
		});
		this.findViewById(R.id.qq_btn_insert_pics).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				 Intent intent = new Intent(Intent.ACTION_PICK, null);  
                 intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);  
                 startActivityForResult(intent, PHOTORESOULT); 
			}
		});
		this.findViewById(R.id.qq_btn_insert_pic).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
                 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
                 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));  
                 startActivityForResult(intent, PHOTOHRAPH); 
			}
		});
		this.findViewById(R.id.qq_ivDelPic).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Dialog dialog = new AlertDialog.Builder(OAuthActivity.this).setTitle(R.string.attention)
				.setMessage(R.string.del_pic).setPositiveButton(R.string.ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int which) {
								mPiclayout.setVisibility(View.GONE);
							}
						}).setNegativeButton(R.string.cancel, null)
				.create();
				dialog.show();
			}
		});
		
		Intent intent = getIntent();
		if (intent.hasExtra("oauth_token")) {
			String oauth_token = intent.getStringExtra("oauth_token");
			String oauth_token_secret = intent.getStringExtra("oauth_token_secret");
			setToken(oauth_token, oauth_token_secret);
		}
	}

	public void onResume() {
		super.onResume();
		Uri uri = this.getIntent().getData();
		if (uri != null) {
			String oauth_verifier = uri.getQueryParameter("oauth_verifier");
			String oauth_token = uri.getQueryParameter("oauth_token");
			getToken(oauth_verifier, oauth_token);
		}
	}
	
	public void getToken(String oauth_verifier, String oauth_token) {
		oauth = TokenStore.oauth;
		auth = TokenStore.auth;
		oauth.setOauth_verifier(oauth_verifier);
		oauth.setOauth_token(oauth_token);
		clientIp = Configuration.wifiIp;
		try {
			oauth = auth.accessToken(oauth);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (oauth.getStatus() == 2) {
			System.out.println("Get Access Token failed!");
			return;
		} else {
			TokenStore.store(this, oauth);
		}
	}

	public void setToken(String oauth_token, String oauth_token_secret) {
		oauth = TokenStore.oauth;
		oauth.setOauth_token(oauth_token);
		oauth.setOauth_token_secret(oauth_token_secret);
	}
	
	@Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (resultCode == NONE)  
            return;  
        if (requestCode == PHOTOHRAPH) {  
            File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");  
            startPhotoZoom(Uri.fromFile(picture));  
        }  
        if (data == null)  
            return;  
        if (requestCode == PHOTOZOOM) {  
            startPhotoZoom(data.getData()); 
        }  
        if (requestCode == PHOTORESOULT) {  
            Bundle extras = data.getExtras();  
            mPiclayout.setVisibility(View.VISIBLE);
            if (extras != null) {  
                Bitmap photo = extras.getParcelable("data");  
                ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
                photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 - 100)压缩文件   
                image.setImageBitmap(photo);  
            }else{
            	image.setImageURI(data.getData());
            	mPicPath = data.getData().toString();
            	mPicPath=mPicPath.replace("file://", "");
            }  
        }  
        super.onActivityResult(requestCode, resultCode, data);  
    }  
	
	 public void startPhotoZoom(Uri uri) {  
	        Intent intent = new Intent("com.android.camera.action.CROP");  
	        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);  
	        intent.putExtra("crop", "true");  
	        intent.putExtra("aspectX", 1);  
	        intent.putExtra("aspectY", 1);  
	        intent.putExtra("outputX", 64);  
	        intent.putExtra("outputY", 64);  
	        intent.putExtra("return-data", true);  
	        startActivityForResult(intent, PHOTORESOULT);  
	    }  
	
}
